/**
 * Created by guo.xiaomin on 2017-10-27.
 */
var commissionService = require('../services/commissionService');
var messageUtil = require('../common/utils/messageUtil');
var nodeExcel = require('excel-export');
var moment = require('moment');
var toolUtil = require('../common/utils/toolUtil');


/*  宝宝树66小区sprint4    add   66后台结算佣金管理.导出订单 luolh  20171027  start   */
exports.exportOrderCommission = function (req, res) {
    // 订单导出
    commissionService.exportCommissionOrderService(req, function (err, result) {
        if (err) {
            logger.error('Exception happen when exportUser...' + err.message);
            var filename="err_no_user.xlsx";
            var conf={
            };
            conf.cols = [{
                caption: '出错',
                type: 'string'
            }];
            conf.rows=[[err.message]];
            conf.name = "error";
            var ret = nodeExcel.execute(conf);
            res.setHeader('Content-Type', 'application/vnd.openxmlformats');
            res.setHeader("Content-Disposition", "attachment; filename=" + filename);
            res.end(ret, 'binary')
        } else {
            var conf={};
            conf.cols= [
                {
                    caption: '订单id',
                    type: 'string'
                },{
                    caption: '下单日期',
                    type: 'string'
                },{
                    caption: '结算状态',
                    type: 'string'
                },{
                    caption: 'UID',
                    type: 'string'
                },{
                    caption: '大使昵称',
                    type: 'string'
                },{
                    caption: '大使手机号码',
                    type: 'string'
                },{
                    caption: '商品名称',
                    type: 'string'
                },{
                    caption: '商品单价',
                    type: 'number'
                },{
                    caption: '商品数量',
                    type: 'number'
                },{
                    caption: '订单优惠总价',
                    type: 'number'
                },{
                    caption: '商品类目佣金比例',
                    type: 'string'
                },{
                    caption: '订单佣金',
                    type: 'number'
                },{
                    caption: '分成比例',
                    type: 'string'
                },{
                    caption: '订单状态',
                    type: 'string',
                    width:58.0
                }];
            var tempRow = [];
            if(result != null && result.length > 0) {
                var dataresult = result;
                for (var i = 0; i < dataresult.length; i++) {
                    var temp = [];
                    // 订单id
                    if (dataresult[i].order_id) {
                        temp.push(dataresult[i]._doc.order_id);
                    } else {
                        temp.push("");
                    }
                    // 下单日期
                    if (dataresult[i].order_time) {
                        // HH 24小时制，hh12小时制
                        temp.push(moment(dataresult[i].order_time).format('YYYY-MM-DD HH:mm:ss'));
                    } else {
                        temp.push("");
                    }
                    // 结算状态
                    if ((dataresult[i]._doc.shareCommissionUser
                        &&dataresult[i]._doc.shareCommissionUser._id.toString() == dataresult[i]._doc.uidVal)
                        || (dataresult[i]._doc.selfPurchaseUser
                        && dataresult[i]._doc.selfPurchaseUser._id.toString()  == dataresult[i]._doc.uidVal)
                        || (dataresult[i]._doc.communityCommissionUser
                        && dataresult[i]._doc.communityCommissionUser._id.toString()  == dataresult[i]._doc.uidVal)) {
                        // 本单结算类型
                        if (dataresult[i]._doc.balanceStatus == 0) {
                            temp.push("未处理");
                        } else if (dataresult[i]._doc.balanceStatus == 1) {
                            temp.push("已粗算");
                        } else if (dataresult[i]._doc.balanceStatus == 2) {
                            temp.push("已精算");
                        } else if (dataresult[i]._doc.balanceStatus == 3) {
                            temp.push("已结算");
                        } else if (dataresult[i]._doc.balanceStatus == 4) {
                            temp.push("已精算");
                        } else if (dataresult[i]._doc.balanceStatus == 5) {
                            temp.push("已结算");
                        }
                    } else {
                        // 提出结算类型
                        if (dataresult[i]._doc.balanceStatus == 0) {
                            temp.push("未处理");
                        } else if (dataresult[i]._doc.balanceStatus == 1) {
                            temp.push("已粗算");
                        } else if (dataresult[i]._doc.balanceStatus == 2) {
                            temp.push("已精算");
                        } else if (dataresult[i]._doc.balanceStatus == 3) {
                            temp.push("已精算");
                        } else if (dataresult[i]._doc.balanceStatus == 4) {
                            temp.push("已结算");
                        } else if (dataresult[i]._doc.balanceStatus == 5) {
                            temp.push("已结算");
                        }
                    }
                    // uid,大使昵称,大使手机号码

                    temp.push(dataresult[i]._doc.uidVal);
                    temp.push(dataresult[i]._doc.nickNameVal);
                    temp.push(dataresult[i]._doc.mobilePhoneVal);

                    // 商品名称
                    if (dataresult[i]._doc.sku_name) {
                        temp.push(dataresult[i]._doc.sku_name);
                    } else {
                        temp.push("");
                    }
                    // 商品价格
                    if (dataresult[i]._doc.price != null) {
                        temp.push(dataresult[i]._doc.price);
                    } else {
                        temp.push("");
                    }
                    // 商品数量
                    if (dataresult[i]._doc.skuQuantity != null) {
                        temp.push(dataresult[i]._doc.skuQuantity);
                    } else {
                        temp.push("");
                    }
                    // 订单优惠总价
                    if (dataresult[i]._doc.skuSubTotal != null) {
                        temp.push(dataresult[i]._doc.skuSubTotal.toFixed(2));
                    } else {
                        temp.push("");
                    }
                    // 商品类目佣金比例
                    if (dataresult[i]._doc.commissionPercent != null) {
                        temp.push((dataresult[i]._doc.commissionPercent * 100).toFixed(2) + "%");
                    } else {
                        temp.push("");
                    }

                    // 订单佣金
                    var total = 0;
                    if ((dataresult[i]._doc.shareCommissionUser
                        &&dataresult[i]._doc.shareCommissionUser._id.toString() == dataresult[i]._doc.uidVal)
                        || (dataresult[i]._doc.selfPurchaseUser
                        && dataresult[i]._doc.selfPurchaseUser._id.toString()  == dataresult[i]._doc.uidVal)
                        || (dataresult[i]._doc.communityCommissionUser
                        && dataresult[i]._doc.communityCommissionUser._id.toString()  == dataresult[i]._doc.uidVal)) {
                        // 本单结算类型
                        if (dataresult[i]._doc.shareCommission) {
                            total += dataresult[i]._doc.shareCommission;
                        }
                        if (dataresult[i]._doc.selfPurchase) {
                            total += dataresult[i]._doc.selfPurchase;
                        }
                        if (dataresult[i]._doc.communityCommission) {
                            total += dataresult[i]._doc.communityCommission;
                        }
                    } else {
                        if (dataresult[i]._doc.inviterCommission) {
                            total += dataresult[i]._doc.inviterCommission;
                        }
                    }

                    temp.push(total);
                    // 分成比例
                    if ((dataresult[i]._doc.shareCommissionUser
                        &&dataresult[i]._doc.shareCommissionUser._id.toString() == dataresult[i]._doc.uidVal)
                        || (dataresult[i]._doc.selfPurchaseUser
                        && dataresult[i]._doc.selfPurchaseUser._id.toString()  == dataresult[i]._doc.uidVal)
                        || (dataresult[i]._doc.communityCommissionUser
                        && dataresult[i]._doc.communityCommissionUser._id.toString()  == dataresult[i]._doc.uidVal)) {
                        temp.push("");
                    } else {
                        temp.push((dataresult[i]._doc.commissionDrawPercentage * 100).toFixed(2)+ "%");
                    }
                    // 订单状态
                    // status: Number, //订单状态（已取消-0,新建-1,待支付-2,拣货中-3,待发货-4,待收货-5,已收货-6,申请取消-8,取消中（等第三方确认）-9,退款完成-100）
                    if (dataresult[i]._doc.status == 0) {
                        temp.push("已取消");
                    } else if (dataresult[i]._doc.status == 1) {
                        temp.push("新建");
                    } else if (dataresult[i]._doc.status == 2) {
                        temp.push("待支付");
                    } else if (dataresult[i]._doc.status == 3) {
                        temp.push("拣货中");
                    } else if (dataresult[i]._doc.status == 4) {
                        temp.push("待发货");
                    } else if (dataresult[i]._doc.status == 5) {
                        temp.push("待收货");
                    } else if (dataresult[i]._doc.status == 6) {
                        temp.push("已收货");
                    } else if (dataresult[i]._doc.status == 8) {
                        temp.push("申请取消");
                    } else if (dataresult[i]._doc.status == 9) {
                        temp.push("取消中");
                    } else if (dataresult[i]._doc.status == 100) {
                        temp.push("退款完成");
                    } else {
                        temp.push("异常单");
                    }
                    tempRow.push(temp);
                }
            }
            var filename="order_commission.xlsx";
            conf.rows=tempRow;
            conf.name = "order_commission";
            var ret = nodeExcel.execute(conf);
            res.setHeader('Content-Type', 'application/vnd.openxmlformats');
            res.setHeader("Content-Disposition", "attachment; filename=" + filename);
            res.end(ret, 'binary');
        }
    });
};
/*  宝宝树66小区sprint4    add   66后台结算佣金管理.导出订单 luolh  20171027  end   */

/*  宝宝树66小区sprint4    add   大使佣金订单详情一览.取得数据 luolh  20171031  start   */
exports.commissionOrderlList = function (req, res) {
    var userId = req.body.userId;
    var startTime = decodeURI(req.body.startTime);
    var endTime = decodeURI(req.body.endTime);

    var size = Number(req.params.size);
    var index = (Number(req.params.page) - 1) * size;

    commissionService.getCommissionOrderlListService(userId,startTime,endTime,size,index, function (err, results) {
        if (err) {
            logger.error('Exception happen when authList...' + err.message);
            res.json(messageUtil.composeFailedMessage(req, 'Exception happen when authList...'));
        } else {
            var data = {
                user:results[0],
                count: results[1]["count"],
                totalPage: results[1]["totalPage"],
                list: results[2]
            };
            res.json(messageUtil.composeSucceededMessage(req, null, data));
        }
    })
};
/*  宝宝树66小区sprint4    add   大使佣金订单详情一览.取得数据 luolh  20171031  end   */

/*  宝宝树66小区sprint4    add   大使佣金订单详情一览.导出订单 luolh  20171031 start   */
exports.exportAmbassadorOrderDatas = function (req, res) {
    var userId = req.cparams.userId;
    var startTime = decodeURI(req.cparams.startTime);
    var endTime = decodeURI(req.cparams.endTime);
    var size = -1;
    var index = -1;
    commissionService.getCommissionOrderlListService(userId,startTime,endTime,size,index, function (err, results) {
        if (err) {
            logger.error('Exception happen when authList...' + err.message);
            res.json(messageUtil.composeFailedMessage(req, 'Exception happen when authList...'));
        } else {
            var data = {
                count: results[1]["count"],
                totalPage: results[1]["totalPage"],
                list: results[2]
            };

            var conf={};
            conf.cols= [
                {
                    caption: '订单id',
                    type: 'string'
                },{
                    caption: '下单日期',
                    type: 'string'
                },{
                    caption: '大使昵称',
                    type: 'string'
                },{
                    caption: '大使手机号码',
                    type: 'string'
                },{
                    caption: '商品名称',
                    type: 'string'
                },{
                    caption: '商品价格',
                    type: 'number'
                },{
                    caption: '商品数量',
                    type: 'number'
                },{
                    caption: '订单优惠总价',
                    type: 'number'
                },{
                    caption: '商品类目佣金比例',
                    type: 'string'
                },{
                    caption: '订单佣金',
                    type: 'number'
                },{
                    caption: '分成比例',
                    type: 'string'
                },{
                    caption: '结算状态',
                    type: 'string'
                },{
                    caption: '订单状态',
                    type: 'string'
                }];
            var tempRow = [];
            var mobilePhone = "";
            if(results[2] != null && results[2].length > 0) {
                var dataresult = results[2];

                for (var i = 0; i < dataresult.length; i++) {
                    var temp = [];
                    // 订单id
                    if (dataresult[i].order_id) {
                        temp.push(dataresult[i]._doc.order_id.toString());
                    } else {
                        temp.push("");
                    }
                    // 下单日期
                    if (dataresult[i].order_time) {
                        // HH 24小时制，hh12小时制
                        temp.push(moment(dataresult[i].order_time).format('YYYY-MM-DD HH:mm:ss'));
                    } else {
                        temp.push("");
                    }
                    // 大使昵称,大使手机号码
                    if (dataresult[i]._doc.shareCommissionUser
                        && results[0]._doc._id.toString() == dataresult[i]._doc.shareCommissionUser._id.toString()) {
                        temp.push(dataresult[i]._doc.shareCommissionUser.nickName);
                        temp.push(dataresult[i]._doc.shareCommissionUser.mobilePhone);
                        if (mobilePhone.length == 0) {
                            mobilePhone = dataresult[i]._doc.shareCommissionUser.mobilePhone;
                        }
                    } else if (dataresult[i]._doc.selfPurchaseUser
                        && results[0]._doc._id.toString() == dataresult[i]._doc.selfPurchaseUser._id.toString()) {
                        temp.push(dataresult[i]._doc.selfPurchaseUser.nickName);
                        temp.push(dataresult[i]._doc.selfPurchaseUser.mobilePhone);
                        if (mobilePhone.length == 0) {
                            mobilePhone = dataresult[i]._doc.selfPurchaseUser.mobilePhone;
                        }
                    } else if (dataresult[i]._doc.communityCommissionUser
                        && results[0]._doc._id.toString() == dataresult[i]._doc.communityCommissionUser._id.toString()) {
                        temp.push(dataresult[i]._doc.communityCommissionUser.nickName);
                        temp.push(dataresult[i]._doc.communityCommissionUser.mobilePhone);
                        if (mobilePhone.length == 0) {
                            mobilePhone = dataresult[i]._doc.communityCommissionUser.mobilePhone;
                        }
                    } else if (dataresult[i]._doc.inviterCommissionUser
                        && results[0]._doc._id.toString() == dataresult[i]._doc.inviterCommissionUser._id.toString()) {
                        temp.push(dataresult[i]._doc.inviterCommissionUser.nickName);
                        temp.push(dataresult[i]._doc.inviterCommissionUser.mobilePhone);
                        if (mobilePhone.length == 0) {
                            mobilePhone = dataresult[i]._doc.inviterCommissionUser.mobilePhone;
                        }
                    } else {
                        temp.push("");
                        temp.push("");
                    }

                    // 商品名称
                    if (dataresult[i]._doc.sku_name) {
                        temp.push(dataresult[i]._doc.sku_name);
                    } else {
                        temp.push("");
                    }
                    // 商品单价
                    if (dataresult[i]._doc.price) {
                        temp.push(dataresult[i]._doc.price);
                    } else {
                        temp.push("");
                    }
                    // 商品数量
                    if (dataresult[i]._doc.skuQuantity) {
                        temp.push(dataresult[i]._doc.skuQuantity);
                    } else {
                        temp.push("");
                    }
                    // 订单优惠总价
                    if (dataresult[i]._doc.skuSubTotal) {
                        temp.push(dataresult[i]._doc.skuSubTotal.toFixed(2));
                    } else {
                        temp.push("");
                    }
                    // 商品类目佣金比例
                    temp.push((dataresult[i]._doc.commissionPercent * 100).toFixed(2) + "%");
                    // 订单佣金
                    var total = 0;
                    if ((dataresult[i]._doc.shareCommissionUser
                             &&dataresult[i]._doc.shareCommissionUser._id.toString() == results[0]._doc._id.toString())
                        || (dataresult[i]._doc.selfPurchaseUser
                            && dataresult[i]._doc.selfPurchaseUser._id.toString()  == results[0]._doc._id.toString())
                        || (dataresult[i]._doc.communityCommissionUser
                            && dataresult[i]._doc.communityCommissionUser._id.toString()  == results[0]._doc._id.toString())) {
                        // 本单结算类型
                        if (dataresult[i]._doc.shareCommission) {
                            total += dataresult[i]._doc.shareCommission;
                        }
                        if (dataresult[i]._doc.selfPurchase) {
                            total += dataresult[i]._doc.selfPurchase;
                        }
                        if (dataresult[i]._doc.communityCommission) {
                            total += dataresult[i]._doc.communityCommission;
                        }
                    } else {
                        if (dataresult[i]._doc.inviterCommission) {
                            total += dataresult[i]._doc.inviterCommission;
                        }
                    }

                    temp.push(total);
                    // 分成比例
                    if ((dataresult[i]._doc.shareCommissionUser
                        &&dataresult[i]._doc.shareCommissionUser._id.toString() == results[0]._doc._id.toString())
                        || (dataresult[i]._doc.selfPurchaseUser
                        && dataresult[i]._doc.selfPurchaseUser._id.toString()  == results[0]._doc._id.toString())
                        || (dataresult[i]._doc.communityCommissionUser
                        && dataresult[i]._doc.communityCommissionUser._id.toString()  == results[0]._doc._id.toString())) {
                        temp.push("");
                    } else {
                        temp.push((commissionDrawPercentage * 100) + "%");
                    }

                    // 结算状态
                    if ((dataresult[i]._doc.shareCommissionUser
                        &&dataresult[i]._doc.shareCommissionUser._id.toString() == results[0]._doc._id.toString())
                        || (dataresult[i]._doc.selfPurchaseUser
                        && dataresult[i]._doc.selfPurchaseUser._id.toString()  == results[0]._doc._id.toString())
                        || (dataresult[i]._doc.communityCommissionUser
                        && dataresult[i]._doc.communityCommissionUser._id.toString()  == results[0]._doc._id.toString())) {
                        // 本单结算类型
                        if (dataresult[i]._doc.balanceStatus == 0) {
                            temp.push("未处理");
                        } else if (dataresult[i]._doc.balanceStatus == 1) {
                            temp.push("已粗算");
                        } else if (dataresult[i]._doc.balanceStatus == 2) {
                            temp.push("已精算");
                        } else if (dataresult[i]._doc.balanceStatus == 3) {
                            temp.push("已结算");
                        } else if (dataresult[i]._doc.balanceStatus == 4) {
                            temp.push("已精算");
                        } else if (dataresult[i]._doc.balanceStatus == 5) {
                            temp.push("已结算");
                        }
                    } else {
                        // 提出结算类型
                        if (dataresult[i]._doc.balanceStatus == 0) {
                            temp.push("未处理");
                        } else if (dataresult[i]._doc.balanceStatus == 1) {
                            temp.push("已粗算");
                        } else if (dataresult[i]._doc.balanceStatus == 2) {
                            temp.push("已精算");
                        } else if (dataresult[i]._doc.balanceStatus == 3) {
                            temp.push("已精算");
                        } else if (dataresult[i]._doc.balanceStatus == 4) {
                            temp.push("已结算");
                        } else if (dataresult[i]._doc.balanceStatus == 5) {
                            temp.push("已结算");
                        }
                    }

                    // 订单状态
                    // status: Number, //订单状态（已取消-0,新建-1,待支付-2,拣货中-3,待发货-4,待收货-5,已收货-6,申请取消-8,取消中（等第三方确认）-9,退款完成-100）
                    if (dataresult[i]._doc.status == 0) {
                        temp.push("已取消");
                    } else if (dataresult[i]._doc.status == 1) {
                        temp.push("新建");
                    } else if (dataresult[i]._doc.status == 2) {
                        temp.push("待支付");
                    } else if (dataresult[i]._doc.status == 3) {
                        temp.push("拣货中");
                    } else if (dataresult[i]._doc.status == 4) {
                        temp.push("待发货");
                    } else if (dataresult[i]._doc.status == 5) {
                        temp.push("待收货");
                    } else if (dataresult[i]._doc.status == 6) {
                        temp.push("已收货");
                    } else if (dataresult[i]._doc.status == 8) {
                        temp.push("申请取消");
                    } else if (dataresult[i]._doc.status == 9) {
                        temp.push("取消中");
                    } else if (dataresult[i]._doc.status == 100) {
                        temp.push("退款完成");
                    } else {
                        temp.push("异常单");
                    }

                    tempRow.push(temp);
                }
            }
            var filename = moment(startTime).format('YYYY-MM-DD') + "_"+mobilePhone+".xlsx";
            conf.rows=tempRow;
            conf.name = "order_detail";
            var ret = nodeExcel.execute(conf);
            res.setHeader('Content-Type', 'application/vnd.openxmlformats');
            res.setHeader("Content-Disposition", "attachment; filename=" + filename);
            res.end(ret, 'binary');
        }
    })
};
/*  宝宝树66小区sprint4    add   66后台结算佣金管理.导出订单 luolh  20171031  end   */



/**宝宝树四期   获取复核日志数据   add pzs 20171031  start**/
exports.getReexamineLogSearch = function(req, res){
    var size = Number(req.params.size);
    commissionService.getReexamineLogSearch(req, function(error, result){
        var list = [];
        result.list.forEach(function(item, index){
            var obj = {};
            obj.order_id = item.order_id;
            obj.order_date = moment(item.order_time).format("YYYY-MM-DD HH:mm:ss");
            obj.log_date = moment(item.dateCreated).format("YYYY-MM-DD HH:mm:ss");

            var comment = "["+item.comment+"]";
            //列：对比结果；
            for (var key in item){
                // console.log("-------key0:" + key);
                if((key.indexOf("new")>=0) || (key.indexOf("old")>=0) || (key.indexOf("error_")>=0) ) { //||
                    if(item[key]){
                        var value = item[key];

                        if(key == "new_refundTime" || key == "old_refundTime" || key=="old_doneTime" || key=="new_doneTime"){
                            if((item.new_refundTime+"" == ""+item.old_refundTime) || (item.old_doneTime+"" == ""+item.new_doneTime) ){
                                continue;
                            }
                            value = moment(value).format("YYYY-MM-DD HH:mm:ss");
                        }

                        comment = comment+key+"="+value+"；";
                    }
                }
            }

            obj.compare = comment;
            obj.is_error = item.isError;
            list.push(obj);
        });
        var totalPage =Math.ceil( result.count/size);
        var data = {
            totalPage:totalPage,
            count:result.count,
        };
        data.list = list;
        res.json(messageUtil.composeSucceededMessage(req, null, data));
    });
};
/**宝宝树四期   获取复核日志数据   add pzs 20171031  end**/

/*  宝宝树66小区sprint4    add   66后台大使佣金结算.搜索 lqj  20171031  start  */
exports.commissionSettlement = function(req, res) {
    //小区大使订单信息显示
    if (req.body.initFlg == true) {
        var data = {
            count: 0,
            totalPage: 0,
            list: [],
            totalInfo :{}
        };
        res.json(messageUtil.composeSucceededMessage(req, null, data));
    } else {
        commissionService.commissionSettlement(req, function(err, results) {
            if (err) {
                logger.error('Exception happen when commissionSettlement...' + err.message);
                res.json(messageUtil.composeFailedMessage(req, 'Exception happen when questionList...'));
            }else {
                // var data = {
                //     count: results[0] ? results[0]["count"] : 0,
                //     totalPage: results[0] ? results[0]["page"] : 0,
                //     list: results[1] ? results[1] : {}
                //
                // };
                //logger.debug('data: ');
                //logger.debug(data);
                //console.log("------------results:"+results);
                res.json(messageUtil.composeSucceededMessage(req, null, results));
            }

        });
    }

};
/*  宝宝树66小区sprint4    add   66后台大使佣金结算.搜索 lqj  20171031  end   */


/*  宝宝树66小区sprint4    add   66后台大使佣金结算.导入 lqj  20171031  start  */
exports.commissionImport = function(req, res) {
    commissionService.commissionImportData(req, function(err, results) {
        if (err) {
            res.json(messageUtil.composeFailedMessage(req, 'Exception happen when communityImport...'));
        }else {
            res.json(messageUtil.composeSucceededMessage(req, null, results));
        }
    });
};
/*  宝宝树66小区sprint4    add   66后台大使佣金结算.导入 lqj  20171031  start  */